﻿using System;
using Autofac;
using FluentValidation;

namespace GiveAQuiz.Web.Validation
{
  /// <summary>
  /// This class serves as a factory for creating 
  /// IValidator objects from the FluentValidation library 
  /// that validate a given type.
  /// </summary>
  public class AutofacValidatorFactory : ValidatorFactoryBase
  {
    /// <summary>
    /// Creates an instance of the AutofacValidationFactory.
    /// </summary>
    /// <param name="container">The Autofac IoC Container.</param>
    public AutofacValidatorFactory(IContainer container)
    {
      Container = container;
    }

    public IContainer Container
    {
      get;
      private set;
    }

    /// <summary>
    /// Factory method used to create IValidator instances mapped to 
    ///  a given Type.
    /// </summary>
    /// <param name="validatorType">The Type of IValidator object that has 
    /// been requested.</param>
    /// <returns>The matching IValidator instance if one has been 
    /// registered in the Autofac IoC Container.</returns>
    public override IValidator CreateInstance(Type validatorType)
    {      
      IValidator validator = Container.ResolveOptional(validatorType) as IValidator;
      return validator;
    }
  }
}